package com.nbgs.demo.service.impl;

import com.nbgs.demo.dao.UpdateConsumptionInfoMapper;
import com.nbgs.demo.info.StageInfo;
import com.nbgs.demo.service.UpdateConsumptionInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UpdateConsumptionInfoServiceImpl implements UpdateConsumptionInfoService {

    @Autowired
    private UpdateConsumptionInfoMapper updateConsumptionEndInfo;

    @Override
    public void updateConsumptionInfo(int consumptionId, double consumptionEnd,double consumptionStart,String type) {

        log.info("id："+consumptionId+","+"起度："+consumptionStart+","
                +"止度："+consumptionEnd+","+"用水性质："+type);
        updateConsumptionEndInfo.updateConsumptionEnd(consumptionId,consumptionEnd);

        double consumptionVolume = consumptionEnd-consumptionStart;

        log.info("当前用水量："+consumptionVolume);

        if(consumptionVolume>0) {
            //根据用水性质来判断来找出所有阶段
            //用来记录上一次的水量最大边界值（梯度计算）
            Double preScope = 0.0;
            //用来记录算出来的水费
            Double payable = 0.0;
            //用一个hashMap集合来存储水量范围id以及水量上线范围
            List<StageInfo> waterScopeInfo = updateConsumptionEndInfo.selectAllScopeInfo(type);
            //用来标记使用量是否大于第一阶段,若大于，就先变为false,方便最后阶梯计价；否则就直接进行查询当前范围id对应的价格计算

            log.info("返回的数据：" + waterScopeInfo.toString());

            boolean bool = true;
            for (StageInfo waterInfo : waterScopeInfo) {
                //根据遍历的用水范围id去找到对应水价格
                double price = updateConsumptionEndInfo.selectCurrentScopeWaterPrice(waterInfo.getStageId());

                if (waterInfo.getStageScope() < consumptionVolume) {
                    payable += (waterInfo.getStageScope() - preScope) * price;
                    preScope = waterInfo.getStageScope();
                    bool = false;
                } else {
                    if (bool) {
                        payable += consumptionVolume * price;
                    } else {
                        payable += (consumptionVolume - preScope) * price;

                    }
                    break;
                }
            }

            //将重新加入的信息算出来放进对应到账单表
            updateConsumptionEndInfo.updatePayable(consumptionId,payable);


        }
    }
}
